package org.freez4.spring.bean.definition;

import org.freez4.spring.ioc.overview.domain.User;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * BeanDefinition Demo。
 *
 * @author 阿坤同学
 * @date 2023/12/6 10:48 AM
 */
public class BeanDefinitionDemo {

    private static final Logger logger = Logger.getLogger(BeanDefinitionDemo.class.getName());

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.register(BeanDefinitionDemo.class);
        applicationContext.registerBeanDefinition("user", createUserBeanDefinition());
        applicationContext.refresh();

        User user = applicationContext.getBean("user", User.class);
        logger.log(Level.INFO, () -> "通过BeanDefinitionBuilder.genericBeanDefinition(Class<?> beanClass)方法注册User Bean到IoC容器中: " + user);
        applicationContext.close();
    }

    /**
     * 创建User BeanDefinition。
     *
     * @return User bean definition。
     * @author 阿坤同学
     * @date 2023/12/6 11:13 AM
     */
    public static AbstractBeanDefinition createUserBeanDefinition() {
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(User.class).getBeanDefinition();
        MutablePropertyValues propertyValues = new MutablePropertyValues();
        propertyValues
                .add("id", 1)
                .add("name", "free")
                .add("age", 29);
        beanDefinition.setPropertyValues(propertyValues);
        beanDefinition.setScope(BeanDefinition.SCOPE_SINGLETON);
        beanDefinition.setLazyInit(true);
        return beanDefinition;
    }
}
